﻿using System;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;

namespace CoreLibrary.Cache {

    public class EntLibCache : AbstractCache {

        private readonly ICacheManager _impl;

        public EntLibCache() {
            _impl = CacheFactory.GetCacheManager();
        }

        protected override void OnInit() {
            Asserts.NotNull(_impl, "EntLib Cache Manager is requried.");
        }

        protected override void OnDestroy() {}
        protected override void OnStart()   {}
        protected override void OnStop()    {}

        protected override CacheItem<T> GetItem<T>(string key) {
            var data = _impl.GetData(key);
            if (data == null || data is T == false) {
                return new CacheItem<T>(false, default(T)) {
                    Key = key
                };
            }
            return new CacheItem<T>(true, (T) data) {
                Key = key
            };
        }

        public override void Remove(string key) {
            _impl.Remove(key);
        }

        public override void Put(string key, object value) {
            _impl.Add(key, value);
        }

        public override void Put(string key, object value, TimeSpan expiration) {
            _impl.Add(
                key, 
                value,
                CacheItemPriority.NotRemovable,
                null,
                new SlidingTime(expiration));
        }

        public int Size {
            get {
                return _impl.Count;
            }
        }

        public void Clear() {
            _impl.Flush();
        }
    }
}